package Template::Convert::HTML;

use warnings;
use Template::Parser;

require Exporter;

our @ISA = qw(Exporter);

our %EXPORT_TAGS = ( 'all' => [ qw(
	
) ] );

our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );

our @EXPORT = qw(
	convert
);

our $VERSION = '0.01';


# convert($text, %options)
sub convert {
	my $parser = Template::Parser->new;
	my $chunks = $parser->split_text(shift);
	my $text;
	my @state;
	while(@$chunks) {
		my $token = shift @$chunks;
		if(ref $token) {
			my ($pre, $line, $tok) = @$token;
			#my ($tt, $val, @tok) = @$tok;
			#print join ':', @$tok;
			my $tt;
			while(@$tok) {
					$tt = shift @$tok;	
					if($tt eq 'IDENT') {
						my $val = shift @$tok;
						$text .= "<TMPL_VAR $val >";
						last;
					}
					elsif($tt eq 'GET') {
						shift @$tok;
					}
					elsif($tt eq 'FOR') {
						$tt = shift @$tok;
						die "Unknown sequence: FOR:$tt at $line" unless $tt eq 'FOREACH';
						push @state, 'LOOP';
						shift @$tok; # must be IDENT
						$text .= '<TMPL_LOOP'. shift(@$tok).'>';
					}
					elsif($tt eq 'END') {
						$tt = shift @$tok;
						die "Unknown sequence: END:$tt at $line" unless $tt eq 'END';

						my $state = pop @state;
						die "END directive without IF, UNLESS or FOREACH earlier at $line" unless defined $state;
						$text .= "</TMPL_$state>";
					}
					else {
						die "Unsupported tag at $line";
					}
			}
		}
		else {
			$text .= shift @$chunks;
		}
	}
	return $text;
}

1;
__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 NAME

Template::Convert::HTML

=head1 SYNOPSIS

  use Template::Convert::HTML;
  use HTML::Template;

  my $text = convert 'foo.tt';
  my $tmpl = HTML::Template->new(salarref => \$text);

=head1 DESCRIPTION

=head2 EXPORT

=head1 SEE ALSO

=head1 AUTHOR

A. D. Solovets, E<lt>asolovets@gmail.comE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009 by A. D. Solovets

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.


=cut
